package com.zy.community.mini.service.my.handle;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.zy.community.common.core.domain.r.ZyResult;
import com.zy.community.community.domain.ZyOwner;
import com.zy.community.community.domain.ZyOwnerRoom;
import com.zy.community.community.domain.ZyOwnerRoomRecord;
import com.zy.community.community.domain.vo.AuditType;
import com.zy.community.community.domain.vo.RoomStatus;
import com.zy.community.community.mapper.ZyOwnerMapper;
import com.zy.community.community.mapper.ZyOwnerRoomMapper;
import com.zy.community.community.mapper.ZyOwnerRoomRecordMapper;
import com.zy.community.framework.security.mini.MiniContextUtils;
import com.zy.community.mini.factory.BindFactory;
import com.zy.community.web.controller.mini.my.handle.dto.AuditingDto;
import com.zy.community.web.controller.mini.my.handle.dto.BindInfoDto;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 我的代办
 */
@Service
public class MiniMyHandleService {
    @Resource
    private ZyOwnerMapper zyOwnerMapper;
    @Resource
    private ZyOwnerRoomMapper zyOwnerRoomMapper;
    @Resource
    private BindFactory bindFactory;

    @Resource
    private ZyOwnerRoomRecordMapper zyOwnerRoomRecordMapper;

    /**
     * 查询等待我审批的数量
     *
     * @param communityId 小区Id
     * @return 代办数量
     */
    @Transactional(readOnly = true)
    public ZyResult<Integer> countWaitMyHandle(Long communityId) {
        String openId = MiniContextUtils.getOpenId();
        if (StringUtils.isEmpty(openId)) return ZyResult.fail(401, "用户未认证");
        ZyOwner zyOwner = zyOwnerMapper.selectOne(new QueryWrapper<ZyOwner>()
                .eq("owner_open_id", openId)
        );
        if (zyOwner == null) return ZyResult.fail(404, "该用户不存在");
        List<ZyOwnerRoom> zyOwnerRooms = zyOwnerRoomMapper.selectList(new QueryWrapper<ZyOwnerRoom>()
                .eq("room_status", "Binding")
                .eq("community_id", communityId)
                .eq("owner_id", zyOwner.getOwnerId())
                .eq("owner_type", "yz")
        );
        if (zyOwnerRooms != null && zyOwnerRooms.size() > 0) {

            List<Long> roomIds = zyOwnerRooms.stream().map(ownerRoom -> ownerRoom.getRoomId()).collect(Collectors.toList());
            Integer count = zyOwnerRoomMapper.selectCount(new QueryWrapper<ZyOwnerRoom>()
                    .in("room_id", roomIds)
                    .eq("room_status", "Auditing")
                    .ne("owner_type", "yz")
            );
            return ZyResult.data(count);
        }
        return ZyResult.data(0);
    }


    /**
     * 获取所有待审批的数据
     *
     * @param communityId 社区Id
     * @return 待审批记录
     */
    public ZyResult<List<BindInfoDto>> findAllHandleInfo(Long communityId) {
        String openId = MiniContextUtils.getOpenId();
        if (StringUtils.isEmpty(openId)) return ZyResult.fail(401, "用户未认证");
        ZyOwner zyOwner = zyOwnerMapper.selectOne(new QueryWrapper<ZyOwner>()
                .eq("owner_open_id", openId)
        );
        if (zyOwner == null) return ZyResult.fail(404, "该用户不存在");
        List<ZyOwnerRoom> zyOwnerRooms = zyOwnerRoomMapper.selectList(new QueryWrapper<ZyOwnerRoom>()
                .eq("room_status", "Binding")
                .eq("community_id", communityId)
                .eq("owner_id", zyOwner.getOwnerId())
                .eq("owner_type", "yz")
        );
        if (zyOwnerRooms != null && zyOwnerRooms.size() > 0) {

            List<Long> roomIds = zyOwnerRooms.stream().map(ownerRoom -> ownerRoom.getRoomId()).collect(Collectors.toList());
            List<BindInfoDto> waitHandleInfo = zyOwnerRoomMapper.findWaitHandleInfo(communityId, roomIds);
            return ZyResult.data(waitHandleInfo);
        }
        return ZyResult.data(new ArrayList<>());
    }

    /**
     * 审批操作
     *
     * @param auditingDto 审批提交的信息
     * @return 审批结果
     */
    @Transactional
    public ZyResult<String> auditOption(AuditingDto auditingDto) {
        String openId = MiniContextUtils.getOpenId();
        if (StringUtils.isEmpty(openId)) return ZyResult.fail(401, "用户未认证");
        ZyOwner zyOwner = zyOwnerMapper.selectOne(new QueryWrapper<ZyOwner>()
                .eq("owner_open_id", openId)
        );
        if (zyOwner == null) return ZyResult.fail(404, "该用户不存在");
        ZyOwnerRoom zyOwnerRoom = zyOwnerRoomMapper.selectById(auditingDto.getOwnerRoomId());
        if (auditingDto.isPass()) {
            zyOwnerRoom.setRoomStatus(RoomStatus.Binding);
        } else {
            zyOwnerRoom.setRoomStatus(RoomStatus.Reject);
        }
        zyOwnerRoomMapper.update(null, new UpdateWrapper<ZyOwnerRoom>()
                .set("room_status", zyOwnerRoom.getRoomStatus().name()).set("update_time", new Date())
                .eq("owner_room_id", auditingDto.getOwnerRoomId())
        );
        ZyOwnerRoomRecord bindRecord = bindFactory.createBindRecord(zyOwnerRoom);
        bindRecord.setRecordAuditOpinion(auditingDto.getOpinion());
        bindRecord.setRecordAuditType(AuditType.App);
        bindRecord.setCreateById(zyOwner.getOwnerId());
        zyOwnerRoomRecordMapper.insert(bindRecord);
        return ZyResult.success("审批成功");
    }


}
